<?php
namespace Admin\Model;

use Think\Model;

class UserModel extends Model{
	const STATE_BAN = 0; /*禁止登陆*/
	const STATE_PROBATION = 1; /*试用期*/
	const STATE_OK = 2; /*正式员工*/
	const STATE_LEAVE = -1; /*离职员工*/
	//后台员工登陆字段
	const USER_LOGIN_FIELD = 'user_id,login_name,nickname,sector_id,role_id,phone,qq,email,weixin,state,is_deleted,last_time,last_ip,sex';

	/**
	 * 获取下属部门员工信息
	 * @param  int     $sector_id     部门ID
	 * @param  boolean $include_me    是否包括自己的部门
	 * @param  boolean $include_leave 是否包括离职员工
	 * @return [type]                 [description]
	 */
	public function subsector_user( $sector_id = false, $include_me = true,$include_leave = false )
	{
		$wheres = array();
		if( $sector_id ){
			$uinfo = self::loadFromSession();
			if( !$uinfo ) return false;
			$sector_id = $uinfo['sector_id'];
		}
		$MSector = D('Sector');
		$secs = $MSector->sub_sector( $sector_id, $include_me);
		$wheres['_string'] = '1=1';
		$wheres['sector_id'] = array('in', $secs );
		if( !$include_leave )
			$wheres['state'] = array('neq', self::STATE_LEAVE );

		$ulist = $this->field("user_id,login_name,nickname,sector_id,role_id")->where( $wheres )->select();
		return $ulist;
	}

	/**
	 * 获取下属岗位员工信息
	 * @param  int     $role_id       岗位ID
	 * @param  boolean $include_me    是否包括自己的岗位
	 * @param  boolean $include_leave 是否包括离职员工
	 * @return [type]                 [description]
	 */
	public function subrole_user( $role_id = false, $include_me = true, $include_leave = false )
	{
		$wheres = array();
		if( !$role_id ){
			$uinfo = self::loadFromSession();
			if( !$uinfo ) return false;
			$role_id = $uinfo['role_id'];
		}
		$MRole = D('Role');
		$roles = $MRole->sub_role( $role_id, $include_me);
		$wheres['_string'] = '1=1';
		$wheres['role_id'] = array('in', $roles );
		if( !$include_leave )
			$wheres['state'] = array('neq', self::STATE_LEAVE );

		$ulist = $this->field("user_id,login_name,nickname,sector_id,role_id")->where( $wheres )->select();
		return $ulist;
	}

	/**
	 *  后台员工登录接口
	 * @param string $uname   用户登录名
	 * @param string $psw     密码
	 * @param string $caption 验证码
	 * @return array  登录结果
	 */
	public function Login( $uname, $psw, $caption = null) 
	{
		$logres = array('r'=>0,'d'=>null,'m'=>'');
		$wheres = array();
		if (!$uname || !$psw) {
			$logres['m'] = "提交参数不完整";
		}
		else {
			$uinfo = null;
			$wheres['login_name'] = array('eq', $uname);
			$uinfo = $this->where( $wheres )->find();
			if ($uinfo) {
				$pass = md6($psw.$uname.$uinfo['create_time']);
				if ($pass == $uinfo['pass']) {
					if( $uinfo['state'] == self::STATE_BAN || $uinfo['state'] == self::STATE_LEAVE){
						$logres['m'] = '客户已经禁止登陆';
					} 
					else {
						$logres['r'] = 1;
						unset( $uinfo['pass'] );
						$logres['d'] = $this->field(self::USER_LOGIN_FIELD )->where( $wheres )->find();
						$logres['m'] = 'OK';
						/*更新客户登陆信息*/
						$dup = array();
						$dup['last_time'] = date('Y-m-d H:i:s');
						$dup['last_ip'] = get_client_ip();
						$this->where( $wheres )->save( $dup );

						/*获取用户分机配置*/
						$Mphone = M('OmSubphone');
						$whereom = array();
						$whereom['admin_no'] = array('eq', $logres['d']['user_id']);
						$ext = $Mphone->field("om_subphone.subphone,om_subphone.admin_no as uid,om_subphone.line_id,oms.omid,oms.ipaddr")
									  ->join("LEFT JOIN om_server oms on oms.omid=om_subphone.omid")
									  ->where( $whereom )
									  ->find();
						if( $ext )
							$logres['d']['ext'] = $ext;
					}
				}
				else
					$logres['m'] = '密码错误';
			}
			else
				$logres['m'] = '用户不存在';
		}

		return $logres;
	}

	/**
	 * 员工更新自己人信息
	 * @param  int 		$uid   			要更新的员工
	 * @param  array 	$updateInfos 	要更新的客户信息
	 * @param  string   $psw            当前用户密码
	 * @param  string   $newPsw			新密码，为空的时候不更细
	 * @return array    更新后的客户信息
	 */
	public function updateUser($uid, $updateInfos, $psw, $newPsw = false )
	{
		$r = array('r'=>0,'d'=>null,'i'=>'');
		$r['i'] = L('SERVER_BUSY');
		$uinfo = self::loadFromSession();
		if( !$uinfo ){
			$r['i'] = "请登陆后进行操作";
		}
		else{
			if( $uinfo['user_id'] == $uid ){
				//验证密码
				$wheres = array();
				$wheres['user_id'] = array('eq', $uinfo['user_id']);
				$uload = $this->where( $wheres )->find();
				$pass = md6($psw.$uload['login_name'].$uload['create_time']);
				if( $pass == $uload['pass'] ){
					$ups = array();
					$ups['nickname'] = trim( $updateInfos['nickname'] );
					$go = true;
					//更新手机号码
					$wheres['user_id'] = array('neq', $uinfo['user_id']);
					if( $updateInfos['phone']){
						$wheres['phone'] = array('eq', $updateInfos['phone']);
						if( $this->where( $wheres )->find()  ){
							$r['i'] = "该电话号码员工已经使用";
							$go = false;
						}
						else
							$ups['phone'] = $updateInfos['phone'];
						unset( $wheres['phone'] );
					}
					else
						$ups['phone'] = null;
					//更新邮箱
					if( $go && $updateInfos['email']){
						$wheres['email'] = array('eq', $updateInfos['email']);
						if( $this->where( $wheres )->find() ){
							$go = false;
							$r['i'] = "该邮箱已经被别人使用";
						}
						else
							$ups['email'] = $updateInfos['email'];
						unset( $wheres['email'] );
					}
					else
						$upds['email'] = null;
					//更新QQ
					if( $go && $updateInfos['qq'] ){
						$wheres['qq'] = array('eq', $updateInfos['qq']);
						if( $this->where( $wheres )->find() ){
							$go = false;
							$r['i'] = "该QQ号码已经被别人很使用";
						}
						else
							$ups['qq'] =  $updateInfos['qq'];
						unset( $wheres['qq']);
					}
					else
						$ups['qq'] = null;
					//更新微信ID
					if( $go && $updateInfos['weixin'] ){
						$wheres['weixin'] = array('eq', $updateInfos['weixin']);
						if( $this->where( $wheres )->find() ){
							$go = false;
							$r['i'] = '该微信ID已经被别人使用';
						}
						else
							$ups['weixin'] = $updateInfos['weixin'];
						unset( $wheres['weixin'] );
					}
					else
						$ups['weixin'] = null;
					if( $go ){
						$wheres['user_id'] = array('eq', $uload['user_id'] );
						//判断是否更新密码
						if( $newPsw ){
							$ups['pass'] = md6($newPsw.$uload['login_name'].$uload['create_time']);
						}
						$count = $this->where( $wheres )->save( $ups );
						$r['r'] = $count ? ( $newPsw ? 2:1) : 0;
						if( $r['r'] ){
							$r['d'] = $this->field( self::USER_LOGIN_FIELD )->where( $wheres )->find();
						}
					}
				}
				else
					$r['i'] = "当前账号密码验证失败";
			}
			else
				$r['i'] = "更新账号资料与当前登陆账号不一致";
		}
		return $r;
	}

	//从session中加载用户信息　
	public static function loadFromSession( $force = false )
	{
		$uinfo = isset($_SESSION[C('ADMIN_HASH_NAME')]) ? $_SESSION[C('ADMIN_HASH_NAME')] : '';
		if( count( $uinfo ) ){
			$uinfos = authcode( $uinfo , "DECODE");
			$arruinfo = unserialize( $uinfos );
			if( $arruinfo && isset( $arruinfo['user_id'])  ){
				return $arruinfo;
			}
		}
		else
			return false;
	}

	//用户修改密码
	public function resetPass($_uid, $_pwd)
	{
		$r = array('r'=>0,'m'=>'服务器忙，请稍候再试 return');
		$wheres = array();
		$pdata = array();
		if( $_uid ){
			$wheres['user_id'] = array('eq' , $_uid);
			$uinfo = $this->field('login_name,create_time')->where($wheres)->find();
			if( $uinfo ){
				$pdata['pass'] = md6($_pwd.$uinfo['login_name'].$uinfo['create_time']);
				$pdata['last_time'] = date('Y-m-d H:i:s');
				$pdata['last_ip'] = get_client_ip();
				$ret = $this->where($wheres)->save($pdata);
				if($ret){
					$r['r'] = 1;
					$r['m'] = "密码重置成功";
				}else{
					$r['m'] = "很抱歉，密码重置失败";
				}
			}else{
				$r['m'] = "很抱歉，查找用户失败";
			}
		}
		return $r;
	}

	//修改部门岗位
	public function changeRoleSector( $uid, $bmid, $gwid)
	{
		$r = array('r'=>0,'m'=>'服务器忙，请稍候再试 return');
		$wheres = array();
		$d = array();
		if ( $uid ) {
			$wheres['user_id'] = array('eq' , $uid);
			$d['sector_id'] = $bmid;
			$d['role_id'] = $gwid;
			$d['last_time'] = date('Y-m-d H:i:s');
			$d['last_ip'] = get_client_ip();
			$editBm = $this->where( $wheres )->save( $d );
			if($editBm){
				$r['r'] = 1;
				$r['m'] = "部门岗位修改成功";
			}else{
				$r['m'] = "很抱歉，部门岗位修改失败";
			}
		}else{
			$r['m'] = "很抱歉，参数传递失败";
		}
		return $r;
	}
	//添加新用户
	public function addUser( $uinfo )
	{
		$r = array('d'=>NULL,'i'=>'','r'=>0);
		$wheres = array();
		$d = array();
		if (!$uinfo || !$uinfo['nickname'] ||!$uinfo['pwd']){
			$r['i'] = "提交参数错误";
			return $r;
		}

		if (!$uinfo['sector_id']) {
			$r['i'] = '部门信息不能为空';
			return $r;
		}
		$uid = 0;
		if (isset($uinfo['phone']) && $uinfo['phone']) {
			$find = $this->_fieldCheck($uid, 'phone', $uinfo['phone']);
			if ($find)
				$r['i'] = "电话号码重复";
		}
		if (isset($uinfo['qq']) && $uinfo['qq']) {
			$find = $this->_fieldCheck($uid, 'qq', $uinfo['qq']);
			if ($find)
				$r['i'] = "QQ号码重复";
		}
		if (isset($uinfo['weixin']) && $uinfo['weixin']) {
			$find = $this->_fieldCheck($uid, 'weixin', $uinfo['weixin']);
			if ($find)
				$r['i'] = "微信号重复";
		}
		if (isset($uinfo['cert_num']) && $uinfo['cert_num']) {
			$find = $this->_fieldCheck($uid, 'cert_num', $uinfo['cert_num']);
			if ($find)
				$r['i'] = "投顾证书编号重复";
		}

		if ($r['i'])
			return $r;
		//生成用户登录名

		$MSector = M('Sector');
        $wheres = array();
        $wheres['sector_id'] = array('eq', $uinfo['sector_id']);
        $team = '';
        $dsector = $MSector->where( $wheres )->find();
        if ($dsector&&$dsector['is_subcompany']) {
        	$team = $dsector['sector_name'];
        }
       	else if ($dsector) {
       		$wheres['sector_id'] = array('eq', $dsector['parent_company']);
       		$team = $MSector->where( $wheres )->getField("sector_name");
       	}
       	if(!$team) {
       		$team = '系统';
       	}
        $wherel = array();
        $login_name =  ff_letter_first( msubstr($team,0,1)).ff_letter_first( msubstr($team,1,1));
        $wherel['login_name'] = array('like', $login_name.'%');
        $lastUser = $this->where( $wherel )->order("user_id desc")->find();
        if($lastUser){
            $ucnt = intval( substr($lastUser['login_name'],2) ) + 1;
        }
        else{
            $ucnt = 1;
        }
        $code = sprintf("%04d",$ucnt);
        $uinfo['login_name'] = $login_name.$code;
		$uinfo['create_time'] = date('Y-m-d H:i:s');
		$uinfo['last_time'] = $uinfo['create_time'];
		$uinfo['last_ip'] = get_client_ip();
		$uinfo['pass'] = md6($uinfo['pwd'].$uinfo['login_name'].$uinfo['create_time']);
		$ret = $this->add( $uinfo );
		if ($ret) {
			$r['r'] = 1;
			$r['data'] = $ret;
			$r['i'] = '用户添加成功';
		} else {
			$r['i'] = '用户添加失败';
		}
		return $r;
	}

 	private function _fieldCheck($uid, $field, $value)
 	{
 		$wherec = array();
		$wherec['user_id'] = array('neq', $uid );
		$wherec[$field] = array('eq', $value);
		if (!$value)
			return 0;
		$cnt = $this->where( $wherec)->count();
		return $cnt ? 1:0;
 	}

	//编辑新用户
	public function updateUserInfo( $uid, $uinfo)
	{
		$r = array('d'=>NULL,'i'=>'','r'=>0);
		$wheres = array();
		$d = array();
		$wheres['user_id'] = array('eq',$uid);
		$ulist = $this->where( $wheres )->find();
		if (!$ulist) {
			$r['i'] = '很抱歉，查找用户失败';
		}
		else if ($ulist&&$ulist['user_id'] == 1){
			$r['i'] = "超级管理员的信息不能编辑";
		}
		else if (!$uinfo){
			$r['i'] = "更新用户不存在";
		}
		else if(!$uinfo || !$uinfo['login_name'] || !$uinfo['nickname']){
			$r['i'] = "提交参数错误";
		}
		else {
			if (isset($uinfo['phone']) && $uinfo['phone']) {
				$find = $this->_fieldCheck($uid, 'phone', $uinfo['phone']);
				if ($find)
					$r['i'] = "电话号码重复";
			}
			if (isset($uinfo['qq']) && $uinfo['qq']) {
				$find = $this->_fieldCheck($uid, 'qq', $uinfo['qq']);
				if ($find)
					$r['i'] = "QQ号码重复";
			}
			if (isset($uinfo['weixin']) && $uinfo['weixin']) {
				$find = $this->_fieldCheck($uid, 'weixin', $uinfo['weixin']);
				if ($find)
					$r['i'] = "微信号重复";
			}
			if (isset($uinfo['cert_num']) && $uinfo['cert_num']) {
				$find = $this->_fieldCheck($uid, 'cert_num', $uinfo['cert_num']);
				if ($find)
					$r['i'] = "投顾证书编号重复";
			}

			if ($r['i'])
				return $r;
			if (isset($uinfo['user_id']))
				unset($uinfo['user_id']);
			$ret = $this->where( $wheres )->save( $uinfo );
			if ($ret){
				$r['r'] = 1;
	            $r['d'] = $this->where( $wheres )->find();
	            $r['i'] = '用户信息更新成功';
			}else{
				$r['i'] = '用户信息更新失败';
			}
		}
		return $r;
	}

	//删除用户
	public function m_user_del( $struid )
	{
		$r = array('r'=>0,'m'=>'服务器忙，请稍候再试 return');
		if (strlen($struid) < 1) {
			$r['m'] = "没有选择删除项";
			return $r;
		}
		$wheres = array();
		$wheres['user_id'] = array('in',$struid);
		$d = array();
		$d['state'] = -1;
		$d['is_deleted'] = 1;
		$delID = $this->where( $wheres )->save( $d );
		if ($delID) {
			$r['r'] = 1;
			$r['m'] = "用户删除成功！";
		} else {
			$r['m'] = "很抱歉，用户删除失败！";
		}
		return $r;
	}

}
?>